package com.truyentranh.utils.sqllite.datasource;

import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;

import com.truyentranh.data.HaiBLMetalData;
import com.truyentranh.data.TamDiemDetailModuleData;
import com.truyentranh.modules.truyentranh.TruyenTranhChapterData;
import com.truyentranh.utils.Logger;
import com.truyentranh.utils.StringUtils;
import com.truyentranh.utils.sqllite.helper.SQLiteHaiBLMetalDataCachedHelper;
import com.truyentranh.utils.sqllite.helper.SQLiteTopicHaiBLHelper;
import com.truyentranh.utils.sqllite.helper.SQLiteTruyenTranhBookmarkHelper;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

@SuppressLint("NewApi")
public class TruyenTranhBookMarkDataSource {

	// Database fields
	private SQLiteDatabase database;
	private SQLiteTruyenTranhBookmarkHelper dbHelper;
	
	public TruyenTranhBookMarkDataSource(Context context) {
		dbHelper = new SQLiteTruyenTranhBookmarkHelper(context);
	}
	
	public void open() throws SQLException {
		Logger.logMe("open data base");
		database = dbHelper.getWritableDatabase();

		if (!isTableExists(SQLiteTruyenTranhBookmarkHelper.TABLE_COMICS, true)) {
			dbHelper.onCreate(database);
		}
	}
	
	public boolean isTableExists(String tableName, boolean openDb) {
		try {
			if (openDb) {
				if (database == null || !database.isOpen()) {
					database = dbHelper.getReadableDatabase();
				}

				if (!database.isReadOnly()) {
					database.close();
					database = dbHelper.getReadableDatabase();
				}
			}

			Cursor cursor = database.rawQuery("select * from '" + tableName + "'", null);
			if (cursor != null) {
				cursor.close();
			}
			return true;
		} catch (Exception e) {

		}
		return false;
	}
	
	public void close() {
		if(database != null && database.isOpen()){
			database.close();
		}
		database = null;
		dbHelper.close();
	}
	
	public boolean deletedTruyenTranh(String readUrl){
		if (database == null) {
			open();
		}
		
		String id = StringUtils.MD5(readUrl);
		
//		Logger.logMe(">>> deleted id" + id);
//		boolean deleted = database.delete(SQLiteTruyenTranhBookmarkHelper.TABLE_COMICS, 
//				SQLiteTruyenTranhBookmarkHelper.COLUMN_ID + "='" + id + "'", null) > 0;
		ContentValues values = new ContentValues();
		if(id != null && !"".equals(id)){			
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_STATE, 0);
		}		
		int mIdInsert = database.update(SQLiteTruyenTranhBookmarkHelper.TABLE_COMICS, values,
				SQLiteTruyenTranhBookmarkHelper.COLUMN_ID + "='" + id+"'", null);
		database.close();
		database = null;				
		close();
		Log.i("insertTruyenTranh", ">>>>>>>>>>>>>>>update");
		return mIdInsert != -1;
	}
	
	public boolean insertTruyenTranh(TruyenTranhBookmark bookmark){
		if (database == null) {
			open();
		}

		ContentValues values = new ContentValues();
		final String id = StringUtils.MD5(bookmark.getCurrentChapter().getUrl());
		
		long mIdInsert = -1;
		
		if(id != null && !"".equals(id)){
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_ID, id);
			
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_TITLE, bookmark.getCurrentComic().getTitle());
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_AVATAR, bookmark.getCurrentComic().getAvatar());
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_HREF, bookmark.getCurrentComic().getHref());
			
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_READURL, bookmark.getCurrentChapter().getUrl());
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_NAME, bookmark.getCurrentChapter().getName());
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_PAGE, bookmark.getCurrentPage());
			
			values.put(SQLiteTruyenTranhBookmarkHelper.COLUMN_STATE, 1);
		}
		
		Cursor cursor = database.rawQuery(" Select * From  " + 
				SQLiteTruyenTranhBookmarkHelper.TABLE_COMICS + " Where "+SQLiteTruyenTranhBookmarkHelper.COLUMN_ID + " = '" + id + "'", null);
		Log.i("insertTruyenTranh", ">>>>>>>>>>>>>>>");
		try{
			if (cursor != null && cursor.getCount() > 0) {
				Log.i("insertTruyenTranh", ">>>>>>>>>>>>>>>cursor.getCount() = "+cursor.getCount());
				Log.i("insertTruyenTranh", ">>>>>>>>>>>>>>>bookmark.getCurrentPage() = "+bookmark.getCurrentPage());
				cursor.close();
				cursor = null;
				
				//update				
				mIdInsert = database.update(SQLiteTruyenTranhBookmarkHelper.TABLE_COMICS, values, SQLiteTruyenTranhBookmarkHelper.COLUMN_ID + "='" + id+"'", null);
				database.close();
				database = null;				
				close();
				Log.i("insertTruyenTranh", ">>>>>>>>>>>>>>>update");
				return mIdInsert != -1;
			} else {
				Log.i("insertTruyenTranh", ">>>>>>>>>>>>>>>bookmark.getCurrentPage() = "+bookmark.getCurrentPage());
				mIdInsert = database.insertWithOnConflict(SQLiteTruyenTranhBookmarkHelper.TABLE_COMICS, null, values, SQLiteDatabase.CONFLICT_IGNORE);
				database.close();
				database = null;				
				close();				
				Log.i("insertTruyenTranh", ">>>>>>>>>>>>>>>insertWithOnConflict");
				return mIdInsert != -1;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	public ArrayList<TruyenTranhBookmark> getAllBookmarks(){
		if (database == null) {
			open();
		}
		
		Cursor cursor = database.rawQuery(" Select * From  " + 
				SQLiteTruyenTranhBookmarkHelper.TABLE_COMICS, null);
		ArrayList<TruyenTranhBookmark> data = new ArrayList<TruyenTranhBookmark>();
		try {
			if (cursor != null && cursor.getCount() > 0) {
				if (cursor.moveToFirst()) {
					do {
						String id = cursor.getString(0);
						
						String title = cursor.getString(1);
						String avatar = cursor.getString(2);
						String href = cursor.getString(3);

						String readUrl = cursor.getString(4);
						String name = cursor.getString(5);
						int page = cursor.getInt(6);
						int active = cursor.getInt(7);

						TruyenTranhBookmark bookmark = new TruyenTranhBookmark();
						bookmark.setCurrentPage(page);
						bookmark.setActive(active);

						TamDiemDetailModuleData detailModuleData = new TamDiemDetailModuleData();
						detailModuleData.title = title;
						detailModuleData.avatar = avatar;
						detailModuleData.href = href;
						bookmark.setCurrentComic(detailModuleData);

						TruyenTranhChapterData chapterData = new TruyenTranhChapterData();
						chapterData.id = id;
						chapterData.readUrl = readUrl;
						chapterData.name = name;
						bookmark.setCurrentChapter(chapterData);
						
						data.add(bookmark);
						
						// do what ever you want here
					} while (cursor.moveToNext());
				}
				
			}
			return data;
		} finally {	
			database.close();
			database = null;
			close();
		}
	}
	
	public Hashtable<String, String> getAllBookMarksIdByReadUrl(){
		if (database == null) {
			open();
		}
		
		Cursor cursor = database.rawQuery(" Select "+SQLiteTruyenTranhBookmarkHelper.COLUMN_ID
				+","+SQLiteTruyenTranhBookmarkHelper.COLUMN_STATE + " From  " + SQLiteTruyenTranhBookmarkHelper.TABLE_COMICS, null);
		Hashtable<String, String> data = new Hashtable<String, String>();
		try {
			if (cursor != null && cursor.getCount() > 0) {
				if (cursor.moveToFirst()) {
					do {
						String id = cursor.getString(0);
						int active = cursor.getInt(1);
						if(active == 1)
							data.put(id, "");
					} while (cursor.moveToNext());
				}			
				return data;
			}
			return null;
		} finally {	
			database.close();
			database = null;
			close();
		}
	}
}
